import { defineStore } from "pinia";
import type { UserState } from "./types/type";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import type { loginFormData, loginResponseData, userInfoResponseData } from '@/api/user/type'
import { constantRoutes, asyncRoutes, anyRoute } from '../../router/routes'
import router from "@/router";
import cloneDeep from 'lodash/cloneDeep'

//动态路由过滤函数
function filterAsyncRoute(asyncRoutes, routes) {
    return asyncRoutes.filter(item => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}
const useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: localStorage.getItem('token'),
            menuRoutes: constantRoutes,
            username: "",
            avatar: "",
            buttons:[]
        }
    },
    actions: {
        async userLogin(data: loginFormData) {
            const res: loginResponseData = await reqLogin(data)
            //登录成功，获取token
            if (res.code === 200) {
                this.token = res.data as string
                localStorage.setItem('token', res.data as string)
                //保证当前async函数返回成功的promise
                return 'ok'
            } else {
                return Promise.reject(new Error(res.data))
            }
        },
        async userInfo() {
            const res: userInfoResponseData = await reqUserInfo()
            if (res.code == 200) {
                this.username = res.data.name
                this.avatar = res.data.avatar
                this.buttons=res.data.buttons
                //根据用户权限属性,动态分配
                const userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoutes), res.data.routes)
                // console.log(res)
                this.menuRoutes = [...constantRoutes, ...userAsyncRoute, ...anyRoute]
                // console.log(this.menuRoutes)
                const temp = [...userAsyncRoute, ...anyRoute]
                temp.forEach(route => {
                    router.addRoute(route)
                })
                return "ok"
            } else {
                return Promise.reject(new Error(res.message))
            }
        },
        async userLogout() {
            const res: any = await reqLogout()
            if (res.code == 200) {
                this.token = ""
                this.username = ""
                this.avatar = ""
                localStorage.removeItem('token')
            } else {
                return Promise.reject(new Error(res.message))
            }
        }
    },
    getters: {

    }
})

export default useUserStore